import { createSlice, createAsyncThunk} from "@reduxjs/toolkit";
import * as API from "../API/http"

let initialState={
    list:[]
}
const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
    getlist(state,action){
        state.list=action.payload
    },
    getadd(state,action){
        state.list.push(action.payload)
    },

 getdel(state,action){
   state.list= state.list.filter(item=>{
        return item.id!==action.payload
    })
 },
 getedit(state,action){
    let i=state.list.findIndex(item=>{
        return item.id==action.payload.id
    })
    state.list[i]=action.payload
 }
  },
});

export const {getlist,getadd ,getedit,getdel} = todosSlice.actions;
export default todosSlice.reducer;
export let async_list=createAsyncThunk('async_list',async(_,store)=>{
let res=await API.httplist()
store.dispatch(getlist(res))
})
export let async_add=createAsyncThunk('async_add',async(obj,store)=>{
  let res=await API.httpadd(obj)
  store.dispatch(getadd(res))
})
export let async_edit=createAsyncThunk('async_edit',async(obj,store)=>{
  let res=await API.httpedit(obj)
  store.dispatch(getedit(res))
})
export let async_del=createAsyncThunk('async_del',async(id,store)=>{
    await API.httpdel(id)
    store.dispatch(getdel(id))
})
export let async_search=createAsyncThunk('async_edit',async(obj,store)=>{
  let res=await  API.httpsearch(obj)
  store.dispatch(getlist(res))
})